from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from django.conf import settings

# 创建 SQLAlchemy 引擎，连接到 GaussDB
DATABASE_URL = f"postgresql+psycopg2://{settings.SQLALCHEMY_DATABASES['USER']}:{settings.SQLALCHEMY_DATABASES['PASSWORD']}@{settings.SQLALCHEMY_DATABASES['HOST']}:{settings.SQLALCHEMY_DATABASES['PORT']}/{settings.SQLALCHEMY_DATABASES['NAME']}"
engine = create_engine(DATABASE_URL, echo=True)

# 创建一个基本类来定义所有模型
Base = declarative_base()

# 创建一个 Session 类来与数据库交互
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def get_db():
    db = Session()
    try:
        yield db
    finally:
        db.close()


# 定义 User 模型
class User(Base):
    __tablename__ = "user_account"

    id = Column(Integer, primary_key=True)
    name = Column(String(30))
    fullname = Column(String(100), nullable=True)

    addresses = relationship("Address", back_populates="user")

    def __repr__(self):
        return f"User(id={self.id!r}, name={self.name!r}, fullname={self.fullname!r})"


# 定义 Address 模型
class Address(Base):
    __tablename__ = "address"

    id = Column(Integer, primary_key=True)
    email_address = Column(String(100))
    user_id = Column(Integer, ForeignKey("user_account.id"))

    user = relationship("User", back_populates="addresses")

    def __repr__(self):
        return f"Address(id={self.id!r}, email_address={self.email_address!r})"


# 在应用启动时，确保数据库和表已创建
def init_db():
    Base.metadata.create_all(bind=engine)

